package com.kenyi.co;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kenyi.co.common.ui.BaseActivity;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.classification.ClassificationFragment;
import com.kenyi.co.ui.home.HomeFragment;
import com.kenyi.co.ui.home.bean.SysVersionBean;
import com.kenyi.co.ui.me.MeFrament;
import com.kenyi.co.ui.me.bean.UserInfoBean;
import com.kenyi.co.ui.update.UpdatePopWindow;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.StringUtils;
import com.kenyi.co.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

import static com.kenyi.co.utils.CommonUtils.getAppVersion;
import static com.yanzhenjie.permission.runtime.Permission.READ_EXTERNAL_STORAGE;
import static com.yanzhenjie.permission.runtime.Permission.READ_PHONE_STATE;
import static com.yanzhenjie.permission.runtime.Permission.WRITE_EXTERNAL_STORAGE;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private Timer mTimer;
    private TimerTask mTimerTask;

    public static final String PUSH_MSG = "pushMsg";
    private HomeFragment mTab01;
    private ClassificationFragment mTab02;
    private MeFrament mTab04;
    /**
     * 底部四个按钮
     */
    private LinearLayout mTabBtnWeixin;
    private LinearLayout mTabBtnFrd;
    private LinearLayout mTabBtnSettings;
    private LinearLayout li_main_content;
    private String type = "0";
    /**
     * 底部四个按钮
     */
    private TextView mIndex;
    private TextView mTi;
    private TextView mMe;
    private ImageView iv_home_bar;
    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;


    /**
     * 退出时间
     */
    private long exitTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // 初始化页卡
        fragmentManager = getSupportFragmentManager();
        setTabSelection(0);
        checkPermission();
        timeUtils();
        getLike();
    }

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }

    protected void setStatusBarCheng() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.main_cheng));//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }

    private void initView() {
        setStatusBar();
        mTabBtnWeixin = (LinearLayout) findViewById(R.id.id_tab_bottom_weixin);
        mTabBtnFrd = (LinearLayout) findViewById(R.id.id_tab_bottom_friend);
        mTabBtnSettings = (LinearLayout) findViewById(R.id.id_tab_bottom_setting);
        li_main_content = findViewById(R.id.li_main_content);
        mIndex = (TextView) findViewById(R.id.tv_tab_home_index);
        mTi = (TextView) findViewById(R.id.tv_tab_home_ti);
        mMe = (TextView) findViewById(R.id.tv_tab_home_me);

        mTabBtnWeixin.setOnClickListener(this);
        mTabBtnFrd.setOnClickListener(this);
        mTabBtnSettings.setOnClickListener(this);

    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     */
    private void setTabSelection(int index) {
        // 重置按钮
        resetBtn();
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                setStatusBar();
                // 当点击了消息tab时，改变控件的图片和文字颜色
                ((ImageButton) mTabBtnWeixin.findViewById(R.id.btn_tab_bottom_weixin))
                        .setImageResource(R.drawable.ic_tab_home_on);
//                mIndex.setTextColor(this.getResources().getColor(R.color.main_cheng));
                if (mTab01 == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    mTab01 = new HomeFragment();
                    transaction.add(R.id.id_content, mTab01);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(mTab01);
                }
                break;
            case 1:
                setStatusBar();
                // 当点击了消息tab时，改变控件的图片和文字颜色
                ((ImageButton) mTabBtnFrd.findViewById(R.id.btn_tab_bottom_friend))
                        .setImageResource(R.drawable.ic_tab_home_fenlie_on);
                if (mTab02 == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    mTab02 = new ClassificationFragment();
                    transaction.add(R.id.id_content, mTab02);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(mTab02);
                }

                break;

            case 2:
                setStatusBarCheng();
                // 当点击了设置tab时，改变控件的图片和文字颜色
                ((ImageButton) mTabBtnSettings.findViewById(R.id.btn_tab_bottom_setting))
                        .setImageResource(R.drawable.ic_tab_home_me_on);
//                mMe.setTextColor(this.getResources().getColor(R.color.main_cheng));
                if (mTab04 == null) {
                    // 如果SettingFragment为空，则创建一个并添加到界面上
                    mTab04 = new MeFrament();
                    transaction.add(R.id.id_content, mTab04);
                } else {
                    // 如果SettingFragment不为空，则直接将它显示出来
                    transaction.show(mTab04);
                }
                break;
            default:
                break;
        }
        // transaction.commit();
        transaction.commitAllowingStateLoss();
    }

    /**
     * 清除掉所有的选中状态。
     */
    private void resetBtn() {
        ((ImageButton) mTabBtnWeixin.findViewById(R.id.btn_tab_bottom_weixin))
                .setImageResource(R.drawable.ic_tab_home_off);
        mIndex.setTextColor(this.getResources().getColor(R.color.text_c2_656565));
        ((ImageButton) mTabBtnFrd.findViewById(R.id.btn_tab_bottom_friend)).setImageResource(R.drawable.ic_tab_home_fenlie_off);
        mTi.setTextColor(this.getResources().getColor(R.color.text_c2_656565));
        ((ImageButton) mTabBtnSettings.findViewById(R.id.btn_tab_bottom_setting))
                .setImageResource(R.drawable.ic_tab_home_me_off);
        mMe.setTextColor(this.getResources().getColor(R.color.text_c2_656565));

    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */

    private void hideFragments(FragmentTransaction transaction) {
        if (mTab01 != null) {
            transaction.hide(mTab01);
        }
        if (mTab02 != null) {
            transaction.hide(mTab02);
        }

        if (mTab04 != null) {
            transaction.hide(mTab04);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_tab_bottom_weixin:
                setTabSelection(0);
                break;

            case R.id.id_tab_bottom_friend:
                setTabSelection(1);
                break;
            case R.id.id_tab_bottom_setting:
                setTabSelection(2);
                break;
            default:
                break;
        }
    }


    public void checkPermission() {
        AndPermission.with(MainActivity.this)
                .runtime()
                .permission(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, READ_PHONE_STATE)

                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {

                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {

                        Toast.makeText(MainActivity.this, "存储权限申请失败！", Toast.LENGTH_SHORT).show();
                        if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions)) {
//                            showSettingDialog(permissions);
                        }
                    }
                })
                .start();
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("首页");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        MobclickAgent.onPageEnd("首页");
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            // 重写键盘事件分发，onKeyDown方法某些情况下捕获不到，只能在这里写
            if ((System.currentTimeMillis() - exitTime) > 2000) {

                ToastUtil.showShort(getApplicationContext(), "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }

    public void getSysVersion() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        Map<String, String> params = new HashMap<>();

        params.put("platform", "1");
        params.put("version", getAppVersion(this));

        Map<String, String> headers = new HashMap<>();
        headers.put("APP-Key", "APP-Secret");

        String url = NetConfig.SYS_UPGRADE;
        OkHttpUtils.get()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;
                        SysVersionBean packlist = gson.fromJson(response, SysVersionBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            if (StringUtils.isNotEmptypro(packlist.getDatas().getVersion())) {

                                final UpdatePopWindow mPopwindow = new UpdatePopWindow(MainActivity.this, response);
                                mPopwindow.showAtLocation(li_main_content, Gravity.CENTER, 0, 0);
                                mPopwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                                    @Override
                                    public void onDismiss() {

                                        mPopwindow.backgroundAlpha(MainActivity.this, 1f);
                                    }
                                });
                            }

                        } else {

                        }

                    }
                });
    }

    /**
     * 倒计时的管理
     */
    public void timeUtils() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            Runnable updateUI = new Runnable() {
                @Override
                public void run() {
                    getSysVersion();
                }
            };

            @Override
            public void run() {
                runOnUiThread(updateUI);
            }
        };
        mTimer.schedule(mTimerTask, 0, 2000);
    }

    /**
     * 首页分类
     */
    public void getLike() {
        Map<String, String> params = new HashMap<>();
        params.put("version", "2");
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", SharepUtils.getString_info(MainActivity.this, SharepUtils.USER_LOGIN_TOKEN));
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        String url = NetConfig.APPUSER_GETUSER;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        SharepUtils.setString_info(MainActivity.this, "0", SharepUtils.USER_IS_LOGIN);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        UserInfoBean packlist = gson.fromJson(response, UserInfoBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
//                            SharepUtils.setString_info(MainActivity.this, packlist.getDatas().getLikeTags().get(0), SharepUtils.USER_FAV_TAGS);

                            SharepUtils.setString_info(MainActivity.this, "1", SharepUtils.USER_IS_LOGIN);
//
                            List<String> tags = new ArrayList<String>();
                            tags = packlist.getDatas().getLikeTags();

                            try {
                                if (tags != null && tags.size() > 0) {
                                    List<String> LikeTags = packlist.getDatas().getLikeTags();
                                    SharepUtils.setShDataList(MainActivity.this, SharepUtils.USER_FAV_TAGS_LIST, LikeTags);

                                }
                            } catch (Exception e) {
                            }

                        }
                    }
                });
    }
}
